<?php

namespace App\Admin\Forms;

use App\Models\Category;
use App\Models\Order;
use App\Models\OrderService;
use App\Models\Todo;
use App\Models\User;
use App\Support\Data;
use Carbon\Carbon;
use Dcat\Admin\Admin;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Form as DcatForm;


class CreateOrder extends Form implements LazyRenderable
{
    use LazyWidget; // 使用异步加载功能

    // 处理请求
    public function handle(array $input)
    {
        // dd($input);
        // 表单参数
        $order_sn = $input['order_sn'] ?? null;

        $service = $input['service'] ?? null;
        // 默认不是全程无忧客户
        $input['is_carefree'] = 0;
        // 判断是否勾选全程无忧套餐
        if ($service) {
            $input['is_carefree'] = 1;
        }

        if (!$order_sn) {
            return $this->response()->error('参数错误');
        }

        if ($input['pay_status'] == 1) {
            $input['pay_datetime'] = Carbon::now();
            $input['order_amount'] = $input['pay_amount'];
        }

        $input['order_customer'] = Admin::user()->id;

        $result = Order::create($input);

        if ($result) {
            OrderService::create(['order_id' => $result->id]);
            // 给所有后台用户创建通知（新建订单通知）
            return $this->response()->success('成功')->refresh();
        } else {
            return $this->response()->error('失败');
        }
    }

    public function form()
    {
        // 获取外部传递参数
        // $id = $this->payload['id'] ?? null;
        $this->text('order_sn')->value('TT' . date('YmdHis') . Data::getOrderSn())->readOnly();
        $this->select('user_id', '绑定客户')->options(User::where('status', 1)->pluck('username', 'id'));
        $this->radio('pay_status', '支付状态')
            ->when(1, function (Form $form) {
                $form->text('pay_amount');
                $form->image('pay_ticket')->saveFullUrl()->autoUpload();
                $form->select('pay_type')->options(Data::getPayType());
            })
            ->options([
                0 => '未支付',
                1 => '已支付',
            ])
            ->default(0);
        $this->checkbox('service', '服务信息')->options(Data::getOrderService())->canCheckAll()->saving(function ($value) {
            // 也可以转化为json
            return implode(',', $value);
        });
        $this->select('language', '稿件语言')->options(['zh' => '中文', 'en' => '英文']);
        $this->array('manuscript', '上传稿件', function ($table) {
            $table->file('manuscript_file', '稿件文件')->saveFullUrl()->autoUpload();
            $table->text('manuscript_number', '稿件字数');
        })->saveAsJson();
        $this->multipleFile('reference_file', '上传参考文件')->saveFullUrl()->autoUpload()->saving(function ($paths) {
            // 也可以转化为json
            return implode(',', $paths);
        });
        $this->textarea('additional', '额外指示');
        $this->select('purpose', '稿件用途')->options(Data::getOrderPurpose());
        $this->select('subject_area', '学科领域')->options(
            Category::where('parent_id', 0)->pluck('title', 'id')
        )
            ->load('discipline', '/getOrderDiscipline');
        $this->select('discipline', '细分学科')->options(function ($id) {
            return  Category::where('id', $id)->pluck('title', 'id');
        });
    }

    // 返回表单数据，如不需要可以删除此方法
    public function
    default()
    {
        return [
            'order_sn'         => '', // 订单编号
            'user_id' => '',        // 绑定客户
            'pay_status' => '',     // 支付状态
            'service' => '',  // 服务信息
            'language' => '', // 稿件语言
            'manuscript' => '', // 上传稿件  jsonarray 稿件url + 字数
            'reference_file' => '', // 参考文件 jsonarray
            'additional' => '', // 额外指示
            'purpose' => '', // 稿件用途
            'subject_area' => '', // 学科领域
            'discipline' => '', // 细分学科
        ];
    }
}
